package model

import (
	"errors"
	"haodayizhi/global"

	"gorm.io/gorm"
)

const TableNameNotification = "notifications"

// Notification mapped from table <notifications>
type Notification struct {
	ID             int64        `gorm:"column:id;type:bigint;primaryKey;autoIncrement:true" json:"id,string" from:"id"`
	SenderEmail    string       `gorm:"column:sender_email;type:varchar(255)" json:"senderEmail" from:"senderEmail"`
	SenderUsername string       `gorm:"column:sender_username;type:varchar(255)" json:"senderUsername" from:"senderUsername"`
	SenderUID      int64        `gorm:"column:sender_uid;type:bigint" json:"senderUid,string" from:"senderUid"`
	Title          string       `gorm:"column:title;type:varchar(255)" json:"title" from:"title"`
	NoticeType     string       `gorm:"column:notice_type;type:enum('important','general')" json:"noticeType" from:"noticeType"`
	Content        string       `gorm:"column:content;type:text" json:"content" from:"content"`
	NoticeTime     global.MTime `gorm:"column:notice_time;type:timestamp" json:"noticeTime" from:"noticeTime"`
	RecipientType  string       `gorm:"column:recipient_type;type:enum('all','specific')" json:"recipientType" from:"recipientType"`
}

// TableName Notification's table name
func (*Notification) TableName() string {
	return TableNameNotification
}

// CreateNotification creates a new Notification in the database.
func (m *Notification) CreateNotification() error {
	if err := global.Db.Create(m).Error; err != nil {
		return err
	}
	return nil
}

// GetNotificationByID retrieves a Notification by its ID from the database.
func (m *Notification) GetNotificationByID(id int64) (*Notification, error) {
	result := global.Db.First(m, id)
	if result.Error != nil {
		if errors.Is(result.Error, gorm.ErrRecordNotFound) {
			return nil, nil // Notification not found
		}
		return nil, result.Error
	}
	return m, nil
}

// UpdateNotification updates an existing Notification in the database.
func (m *Notification) UpdateNotification() error {
	if err := global.Db.Save(m).Error; err != nil {
		return err
	}
	return nil
}

// DeleteNotification deletes a Notification by its ID from the database.
func (m *Notification) DeleteNotification(id int64) error {
	if err := global.Db.Delete(m, id).Error; err != nil {
		return err
	}
	return nil
}

// 查询到指定多个通知id的通知内容 去重
func (m *Notification) GetNotificationsByIDs(ids []int64) ([]Notification, error) {
	var notifications []Notification
	if err := global.Db.Where("id IN (?)", ids).Order("notice_time desc").Find(&notifications).Error; err != nil {
		return nil, err
	}
	return notifications, nil
}
